package com.cmcc.aregister.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cmcc.aregister.MyApplication;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.asntask.InterfaceUtils.Ad_bar;
import com.cmcc.aregister.cs.asntask.InterfaceUtils.Click_ad_listener;
import com.cmcc.aregister.cs.asntask.InterfaceUtils.DataCallback_09;
import com.cmcc.aregister.cs.asntask.MyAsynTaskOther;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.model.AdModel;
import com.cmcc.aregister.cs.model.AdbarResultModel;
import com.cmcc.aregister.cs.model.ClickAdResultModel;
import com.cmcc.aregister.cs.model.Hospital;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.cmcc.aregister.ui.adapter.ImagePagerAdapter;
import com.cmcc.aregister.ui.view.PageControlView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

/**
 * 首页
 */
public class IndexActivity extends ParentActivity implements OnClickListener {
	private ViewPager ad_image;
	private TextView ad_text;
	private PageControlView page_control;
	private LinearLayout top_left;
	private LinearLayout top_right;
	private LinearLayout center_layout;
	private LinearLayout bottom_left;
	private LinearLayout bottom_right;
	private boolean isFirstCreate = false;
	private Button login_btn;

	private String[] adString;
	
	private DisplayImageOptions options;
	private ImagePagerAdapter mImagePagerAdapter;
	AdbarResultModel mAdbarResultModel;
	Ad_bar ad_bar = new Ad_bar() {

		@Override
		public void ad_bar_callback(AdbarResultModel model) {
			// TODO Auto-generated method stub
			mAdbarResultModel = model;
			if(model.resultCode.equals("0")){
				hasDownBannerAd = true;
				options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.ad_default_bg)
				.cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACT)
				.build();
				mImagePagerAdapter = new ImagePagerAdapter(IndexActivity.this, model.ads, options,mDataCallback_09);
				ad_image.setAdapter(mImagePagerAdapter);
//				gallery.setOnItemSelectedListener(onItemSelectedListener);
//				gallery.setOnItemClickListener(onItemClickListener);
				page_control.count = model.ads.size();
				page_control.generatePageControl(0);
				ad_image.setOnPageChangeListener(mOnPageChangeListener);
				ad_text.setText(mAdbarResultModel.ads.get(0).title);
				if(model.ads.size() > 1){
					bannerStartHandler.postDelayed(bannerStartRun, Integer.parseInt(model.ads.get(0).playtime) * 1000);
				}
			}else{
				if(model.resultMsg.equals("")){
					Toast.makeText(IndexActivity.this, R.string.network_fail, Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(IndexActivity.this, model.resultMsg, Toast.LENGTH_SHORT).show();
				}
			}
		}
	};
	Handler bannerStartHandler = new Handler();
	Runnable bannerStartRun = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			ad_image.setCurrentItem(1);
		}
	};
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(bannerStartHandler != null && bannerStartRun != null){
			bannerStartHandler.removeCallbacks(bannerStartRun);
		}
	}
	
	/**
	 * 初始化参数
	 * @param parameterMap
	 * @return
	 */
	private Map<String,String> initArgMap(Map<String,String> parameterMap){
		parameterMap.put("userId", Arguments.UserId_AD);
		parameterMap.put("timestamp", ConfigUtilHelper.getStringNow());
		parameterMap.put("userPwd", ConfigUtilHelper.getAdUserPwd());
		return parameterMap;
	}
	@Override
	protected void onStop() {
		ImageLoader.getInstance().stop();
		super.onStop();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		isFirstCreate = true;
		init(R.layout.p_index);
	}

	@Override
	protected void setupData() {
		adString = getResources().getStringArray(R.array.ad_title);
	}

	@Override
	protected void setupView() {
		ad_image = (ViewPager) findViewById(R.id.ad_image);
		ad_text = (TextView) findViewById(R.id.ad_text);
		page_control = (PageControlView) findViewById(R.id.pageControlView);
		login_btn = (Button) findViewById(R.id.login_btn);
		top_left = (LinearLayout) findViewById(R.id.top_left);
		top_right = (LinearLayout) findViewById(R.id.top_right);
		center_layout = (LinearLayout) findViewById(R.id.center);
		bottom_left = (LinearLayout) findViewById(R.id.bottom_left);
		bottom_right = (LinearLayout) findViewById(R.id.bottom_right);
		top_left.setOnClickListener(this);
		top_right.setOnClickListener(this);
		center_layout.setOnClickListener(this);
		bottom_left.setOnClickListener(this);
		bottom_right.setOnClickListener(this);
		top_left.setOnLongClickListener(onLongClickListener);
		top_right.setOnLongClickListener(onLongClickListener);
		center_layout.setOnLongClickListener(onLongClickListener);
		bottom_left.setOnLongClickListener(onLongClickListener);
		bottom_right.setOnLongClickListener(onLongClickListener);
		
		
		
//		AdImageAdapter adapter = new AdImageAdapter(context);
//		ad_image.setAdapter(adapter);
//		ad_image.setOnItemSelectedListener(onItemSelectedListener);
//		ad_image.setOnItemClickListener(mOnItemClickListener);
//		page_control.count = 4;
		ad_image.setCurrentItem(0);
		login_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent_1 = new Intent(IndexActivity.this,
						UserLoginActivity.class);
				intent_1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent_1);
			}
		});
		/** 增加默认广告图片  */
		List<AdModel> defAdModels = new ArrayList<AdModel>();
		defAdModels.add(new AdModel());
		options = new DisplayImageOptions.Builder()
        .showImageForEmptyUri(R.drawable.ad_default_bg)
        .cacheOnDisc()
        .imageScaleType(ImageScaleType.EXACT)
        .build();
        mImagePagerAdapter = new ImagePagerAdapter(IndexActivity.this, defAdModels, options,mDataCallback_09);
        ad_image.setAdapter(mImagePagerAdapter);
		if(ConfigUtilHelper.getAutoLogin(this) && !ConfigUtilHelper.isLogin(this)){
			initLogin();
		}
	}

	private void initLogin(){
		Intent intent = new Intent(this,
				UserLoginActivity.class);
		intent.putExtra(Arguments.AUTO_LOGIN, true);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}
	
	OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterview, View view, int i,
				long l) {
			// TODO Auto-generated method stub
			gotoHospitalDetail(i);
//			gotoHospitals();
		}
	};
	
	/**
	 * 进入医院详情
	 * @param type
	 * @param area_type
	 * @param uuid
	 * @param positon
	 */
	private void gotoHospitalDetail(int i){
		Hospital hospital = MyApplication.getInstance().adHospitals.get(i);
		Map<String, Object> httpMap = new HashMap<String, Object>();
		PotoalParcelable potoal = new PotoalParcelable(httpMap);
		Intent intent = null;
		intent = new Intent(IndexActivity.this,
				HospitalDetailActivity.class);
		httpMap.put(Arguments.ACTIVITY_JUMP_HOSPITAL,
				hospital);
		httpMap.put(Arguments.ACTIVITY_JUMP_AREA_TYPE,
				hospital.area_type);
		httpMap.put(Arguments.ACTIVITY_JUMP_POSITION, i);
		intent.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}
	
	/**
	 * 进入医院列表
	 */
	/*private void gotoHospitals(){
		Intent intent = null;
		intent = new Intent(IndexActivity.this, MainActivity.class);
		intent.putExtra(Arguments.INTENT_TO_MAIN_ID, 1);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}*/
	
	OnLongClickListener onLongClickListener = new OnLongClickListener() {

		@Override
		public boolean onLongClick(View v) {
			/*if(v == bottom_left || v == center_layout){
				if(!ConfigUtilHelper.isLogin(IndexActivity.this)){
					gotoLogin();
					return false;
				}
			}*/
			if(!ConfigUtilHelper.isLogin(IndexActivity.this)){
                gotoLogin();
                return false;
            }
			int id = v.getId();
			Intent intent = null;
			int menu_id = 0;
			switch (id) {
			case R.id.top_left:
				intent = new Intent(IndexActivity.this, MainActivity.class);
				menu_id = 0;
				break;
			case R.id.top_right:
				intent = new Intent(IndexActivity.this, MainActivity.class);
				menu_id = 1;
				break;
			case R.id.center:
				intent = new Intent(IndexActivity.this, MainActivity.class);
				menu_id = 4;
				//menu_id = 5;
				break;
			case R.id.bottom_left:
				intent = new Intent(IndexActivity.this, MainActivity.class);
				menu_id = 2;
				break;
			case R.id.bottom_right:
				intent = new Intent(IndexActivity.this, MainActivity.class);
				menu_id = 3;
				break;
			}
			startAnimal(id);
			intent.putExtra(Arguments.INTENT_TO_MAIN_ID, menu_id);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			begin(intent);
			return false;
		}
	};

	/**
	 * 睡眠2秒后进入主页
	 */
	private void begin(final Intent intent) {
		AsyncTask<String, Integer, String> task = new AsyncTask<String, Integer, String>() {
			protected String doInBackground(String... params) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String result) {
				startActivity(intent);
			}
		};
		task.execute("");
	}

	/**
	 * 启动动画
	 * 
	 * @param id
	 *            当前点击view的id
	 */
	public void startAnimal(int id) {
		top_left.setEnabled(false);
		top_right.setEnabled(false);
		center_layout.setEnabled(false);
		bottom_left.setEnabled(false);
		bottom_right.setEnabled(false);
		switch (id) {
		case R.id.top_left:
			top_left.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_center));
			top_right.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_top));
			center_layout.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_center));
			bottom_left.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_bottom));
			bottom_right.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_right));
			break;
		case R.id.top_right:
			top_left.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_left));
			top_right.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_center));
			center_layout.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_center));
			bottom_left.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_bottom));
			bottom_right.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_right));
			break;
		case R.id.center:
			top_left.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_left));
			top_right.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_top));
			center_layout.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_center));
			bottom_left.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_bottom));
			bottom_right.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_right));
			break;
		case R.id.bottom_left:
			top_left.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_left));
			top_right.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_top));
			center_layout.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_center));
			bottom_left.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_center));
			bottom_right.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_right));
			break;
		case R.id.bottom_right:
			top_left.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_left));
			top_right.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_top));
			center_layout.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_center));
			bottom_left.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_bottom));
			bottom_right.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.anim_center));
			break;
		}
	}

	/**
	 * 返回首页时，启动恢复动画
	 */
	public void resumStartAnimal() {
		top_left.startAnimation(AnimationUtils.loadAnimation(context,
				R.anim.anim_left_resume));
		top_right.startAnimation(AnimationUtils.loadAnimation(context,
				R.anim.anim_top_resume));
		center_layout.startAnimation(AnimationUtils.loadAnimation(context,
				R.anim.anim_center_resume));
		bottom_left.startAnimation(AnimationUtils.loadAnimation(context,
				R.anim.anim_bottom_resume));
		bottom_right.startAnimation(AnimationUtils.loadAnimation(context,
				R.anim.anim_right_resume));
		top_left.setEnabled(true);
		top_right.setEnabled(true);
		center_layout.setEnabled(true);
		bottom_left.setEnabled(true);
		bottom_right.setEnabled(true);
	}
boolean hasDownBannerAd = false;
	/**
	 * 根据是否为第一次加载，启动恢复动画
	 */
	@Override
	protected void onResume() {
		super.onResume();
		
		
		if (!isFirstCreate) {
			resumStartAnimal();
		}
		isFirstCreate = false;
		/*if (ConfigUtilHelper.isLogin(app)) {
			login_btn.setVisibility(View.GONE);
		} else {
			login_btn.setVisibility(View.VISIBLE);
		}*/
		if(!hasDownBannerAd){//如果没有加载广告条
			Map<String, String> parameterMap = new HashMap<String, String>();
			parameterMap = initArgMap(parameterMap);
			parameterMap.put("methodVit", Arguments.GetAdBar);
			parameterMap.put("areaId", Arguments.AreaId);
			new MyAsynTaskOther(ad_bar, GlobalSetting.AD_BAR, parameterMap).execute();
		}
	}

	@Override
	public void onClick(View v) {
		/*if(v == bottom_left || v == center_layout){
			if(!ConfigUtilHelper.isLogin(IndexActivity.this)){
				gotoLogin();
				return;
			}
		}*/
		if(!ConfigUtilHelper.isLogin(IndexActivity.this)){
            gotoLogin();
            return;
        }
		int id = v.getId();
		Intent intent = null;
		int menu_id = 0;
		switch (id) {
		case R.id.top_left:
			intent = new Intent(this, MainActivity.class);
			menu_id = 0;
			break;
		case R.id.top_right:
			intent = new Intent(this, MainActivity.class);
			menu_id = 1;
			break;
		case R.id.center:
			intent = new Intent(this, MainActivity.class);
			menu_id = 4;
			/** added by fl 和之前more位置以区分 */
            //menu_id = 5;
			break;
		case R.id.bottom_left:
			intent = new Intent(this, MainActivity.class);
			menu_id = 2;
			break;
		case R.id.bottom_right:
			intent = new Intent(this, MainActivity.class);
			menu_id = 3;
			break;
		}
		startAnimal(id);
		intent.putExtra(Arguments.INTENT_TO_MAIN_ID, menu_id);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		begin(intent);
	}

	/**
	 * 刷新广告图片
	 */
	Handler galleryHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int position = (Integer) msg.obj + 1;
			/*if (position < 4) {
				ad_image.setSelection(position);
			} else {
				ad_image.setSelection(0);
			}*/
			ad_image.setCurrentItem(position);
		}
	};

	OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int position, long arg3) {
			page_control.generatePageControl(position);
			ad_text.setText(adString[position]);
			galleryHandler.removeMessages(0);
			galleryHandler.sendMessageDelayed(
					galleryHandler.obtainMessage(0, position), 2000);
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			showConfirmDialog(R.string.logout_info);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	// 跳转到登陆界面
	private void gotoLogin() {
		Intent intent = new Intent(IndexActivity.this,
				UserLoginActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}
	int bannerCurrentPosition;
	/**
	 * banner点击事件回调
	 */
	DataCallback_09 mDataCallback_09 = new DataCallback_09() {
		
		@Override
		public void callback(int p) {
			// TODO Auto-generated method stub
			if(hasDownBannerAd && mAdbarResultModel.ads.get(p).hasAdUrl.equals("1")){
				bannerCurrentPosition = p;
				showProgressDialog();
				Map<String, String> parameterMap = new HashMap<String, String>();
				parameterMap = initArgMap(parameterMap);
				parameterMap.put("methodVit", Arguments.GetClickAdBar);
				parameterMap.put("areaId", Arguments.AreaId);
				parameterMap.put("adId", mAdbarResultModel.ads.get(p).id);
				new MyAsynTaskOther(mClick_ad_listener, GlobalSetting.CLICK_AD_BAR, parameterMap).execute();
			}
			
		}
	};
	
	Click_ad_listener mClick_ad_listener = new Click_ad_listener() {
		
		@Override
		public void click_ad_callback(ClickAdResultModel mClickAdResultModel) {
			dismissProgressDialog();
			// TODO Auto-generated method stub
			if(mClickAdResultModel.resultCode.equals("0")){
				if(mAdbarResultModel.ads.get(bannerCurrentPosition).scantype.equals("1")
						&& mAdbarResultModel.ads.get(bannerCurrentPosition).hasAdUrl.equals("1")){
					Intent intent = new Intent(IndexActivity.this, MyWebView.class);
					intent.putExtra("url",mClickAdResultModel.url);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
				}
			}
		}
	};
	
	/**
	 * viewPage切换
	 */
	OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {
		
		@Override
		public void onPageSelected(int position) {
			// TODO Auto-generated method stub
			
			if(mAdbarResultModel.ads.size() > 0){
				int p = position % mAdbarResultModel.ads.size();
				page_control.generatePageControl(p);
				ad_text.setText(mAdbarResultModel.ads.get(p).title);
				galleryHandler.removeMessages(0);
				int playTime = 2 *1000;
				if(!mAdbarResultModel.ads.get(p).playtime.equals("")){
					playTime = Integer.parseInt(mAdbarResultModel.ads.get(p).playtime) * 1000;
				}
				galleryHandler.sendMessageDelayed(
						galleryHandler.obtainMessage(0, position), playTime);
			}
			
		}
		
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub
			
		}
	};
	
}